﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraGrid.Views.Grid.Drawing;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraEditors.Drawing;
using DevExpress.XtraGrid.Columns;
namespace ddb_BT1
{
    public partial class frmHoaDonBanHang : DevExpress.XtraEditors.XtraForm
    {
        public frmHoaDonBanHang()
            : this(string.Empty)
        {
        }
        public frmDanhSachHDBanHang frm;
        DataProviderAdapter _AdapterGridview = new DataProviderAdapter();
        DataProviderAdapter _AdapterHoaDon = new DataProviderAdapter();
        DataProviderAdapter _AdapterKhachHang = new DataProviderAdapter();
        SqlDataAdapter Dagrid = new SqlDataAdapter();
        DataTable Dt_grid = new DataTable();
        private DataTable Data_Chitiet_HD;
        private DataTable Data_KhachHang;
        string MAKH;
        string SOHD;
        string SOHDTT = "";
        public frmHoaDonBanHang(string STT)
        {
            BindingSource bs = new BindingSource();
            InitializeComponent();
            this.SearchLookUpHangHoa.EditValueChanged += new System.EventHandler(this.searchLookUpEdit1_EditValueChanged);
            SOHD = STT;
            SLUE_DVKH.Properties.DataSource = DataProvider.getDataTable("select * from KHACHHANG");
            if (!string.IsNullOrEmpty(STT))
            {

                //    Data_Chitiet = DataProvider.getDataTable(string.Format("select * from HOADON_BANHANG where STT_HOADON_BH='{0}'", "HDBH00001"));
                Data_Chitiet_HD = _AdapterHoaDon.getDataTable(string.Format("select * from HOADON_BANHANG where STT_HOADON_BH='{0}'", STT));
                if (Data_Chitiet_HD != null)
                {
                    MAKH = (string)Data_Chitiet_HD.Rows[0]["MA_KHACHHANG"];
                    Data_KhachHang = _AdapterKhachHang.getDataTable(string.Format("select * from KHACHHANG where MAKH='{0}'", MAKH));
                }
                txtLyDo.Text = Data_Chitiet_HD.Rows[0]["LYDO"].ToString();
                txtNgayHD.Text = Data_Chitiet_HD.Rows[0]["NGAYBAN"].ToString();
                cbbLoaiHoaDon.Text = Data_Chitiet_HD.Rows[0]["LOAIHD"].ToString();
               
                  bs.DataSource=  _AdapterGridview.getDataTable(string.Format("select * from CHITIET_HOADON_BH where STT_HOADON_BH='{0}'", STT));
                  bindingNavigator1.BindingSource = bs;
                gridControl1.DataSource = bs;
                SLUE_DVKH.EditValue = MAKH;
            }
            else
            {
                btnDelete.Enabled = false;
                btnInPhieuXK.Enabled = false;
                btnIn.Enabled = false;
                gridControl1.DataSource = _AdapterGridview.getDataTable(string.Format("select * from CHITIET_HOADON_BH where STT_HOADON_BH='{0}'", "ABC1DSF"));
                _AdapterHoaDon.getDataTable(string.Format("select * from HOADON_BANHANG where STT_HOADON_BH='{0}'", "ABCD124"));
                DataTable dt = DataProvider.getDataTable("select top 1 STT_HOADON_BH from HOADON_BANHANG order by STT_HOADON_BH DESC");
                int i = int.Parse(dt.Rows[0][0].ToString().Substring(4, 5));
                ++i;
                string SOHDTT1 = "HDBH" + i.ToString().PadLeft(5, '0');
                SOHDTT = SOHDTT1;
            }
        }
        private DataTable table = new DataTable();
        private void frmHoaDonBanHang_Load(object sender, EventArgs e)
        {


            SearchLookUpHangHoa.DataSource = DataProvider.getDataTable("select * from HANGHOA");

            repositoryItemGridLookUpEdit_TKNO.DataSource = DataProvider.getDataTable("select MA_TAIKHOAN,TEN_TAIKHOAN from DANHMUC_TAIKHOAN where (MA_TAIKHOAN>=1121 and MA_TAIKHOAN<=1123) or (MA_TAIKHOAN>=6411 and MA_TAIKHOAN<=6418)");
            repositoryItemGridLookUpEdit_TKCO.DataSource = DataProvider.getDataTable("select MA_TAIKHOAN,TEN_TAIKHOAN from DANHMUC_TAIKHOAN where (MA_TAIKHOAN>=5111 and MA_TAIKHOAN<=5123) or MA_TAIKHOAN=1388 or MA_TAIKHOAN=3339 ");


            TinhTongTien();

        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            if (SLUE_DVKH.EditValue == "")
            {
                dxErrorProvider1.SetError(SLUE_DVKH, "Bạn phải nhập ô này");
                return;
            }
            if (txtLyDo.Text == "")
            {
                dxErrorProvider1.SetError(txtLyDo, "Bạn phải nhập ô này");
                return;
            }
            try
            {
                DateTime.Parse(txtNgayHD.Text);
            }
            catch
            {
                XtraMessageBox.Show("Bạn nhập ngày không hợp lệ", "Thông báo");
                return;
            }

            if (!string.IsNullOrEmpty(SOHD))
            {
                //Lấy ra dòng dữ liệu đang được chọn trong DataSet
                DataRow dr = _AdapterHoaDon.Table.Rows.Find(SOHD);

                //Bắt đầu chỉnh sửa dữ liệu
                dr.BeginEdit();

                //Cập nhật
                dr["LYDO"] = txtLyDo.Text;
                dr["MA_KHACHHANG"] = SLUE_DVKH.EditValue;
                dr["NGAYBAN"] = txtNgayHD.Text;
                dr["NGAYPHATHANH"] = txtNgayHD.Text;
                dr["LOAIHD"] = cbbLoaiHoaDon.Text;

                dr.EndEdit();
            }
            else
            {

                DataRow dr = _AdapterHoaDon.Table.NewRow();
                dr["STT_HOADON_BH"] = SOHDTT;
                dr["NGAYPHATHANH"] = txtNgayHD.Text;
                dr["LYDO"] = txtLyDo.Text;
                dr["MA_KHACHHANG"] = SLUE_DVKH.EditValue;
                dr["NGAYBAN"] = txtNgayHD.Text;
                dr["LOAIHD"] = cbbLoaiHoaDon.Text;
                _AdapterHoaDon.Table.Rows.Add(dr);
                SOHD = SOHDTT;
            }
            _AdapterHoaDon.Insert_Update();
            _AdapterGridview.Insert_Update();
            XtraMessageBox.Show("Cập nhật hóa đơn thành công");
            btnIn.Enabled = true;
            btnDelete.Enabled = true;
            btnInPhieuXK.Enabled = true;
        }


        private void simpleButton2_Click(object sender, EventArgs e)
        {
            dxErrorProvider1.ClearErrors();
            DataTable dt = new DataTable();

            dt = _AdapterGridview.getDataTable(string.Format("select * from CHITIET_HOADON_BH ct, hanghoa hh where STT_HOADON_BH='{0}' and ct.mahang=hh.mahang",SOHD)); ;
            frmReport_HoaDonBH frm = new frmReport_HoaDonBH(dt, txtTenKH.Text, txtKHDiaChi.Text, txtKHSDT.Text, txtKHMaSoThue.Text, DateTime.Parse(txtNgayHD.Text), lblChuTongTienHang.Text);
            frm.Show();
        }

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {

            SearchLookUpEdit edit = sender as SearchLookUpEdit;
            int rowHandle = edit.Properties.GetIndexByKeyValue(edit.EditValue);
            object row = edit.Properties.View.GetRow(rowHandle);
            string gia = (row as DataRowView).Row["GIAVON"].ToString();

            DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)gridView1;
            view.ActiveEditor.IsModified = true;
            gridView1.SetFocusedRowCellValue("DONGIAVON", gia);
            gridView1.SetFocusedRowCellValue("DONGIA", gia);
            gridView1.SetFocusedRowCellValue("TIENVON", gia);
            gridView1.SetFocusedRowCellValue("THANHTIEN", gia);
            gridView1.SetFocusedRowCellValue("TIENTHUE", 0);
            TinhTongTien();
        }

        private void gridView1_InvalidValueException(object sender, InvalidValueExceptionEventArgs e)
        {
            if (e.ErrorText.Contains("Input string was not in a correct format."))
            {
                e.ErrorText = "Bạn nhập dữ liệu không đúng";
                if (e.Value == "") e.ErrorText = "Bạn phải điền dữ liệu ô này";
            }
        }

        private void txtTenKH_EditValueChanged(object sender, EventArgs e)
        {

        }

        private void labelControl1_Click(object sender, EventArgs e)
        {

        }

        private void gridControl1_KeyDown(object sender, KeyEventArgs e)
        {

            if (gridView1.RowCount > 0 && (e.KeyCode == Keys.Delete))
            {
                if (XtraMessageBox.Show(string.Format("Bạn có chắn chắn muốn xóa không?"), "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    _AdapterGridview.Table.Rows[gridView1.FocusedRowHandle].Delete();
                    gridView1.RefreshData();
                }
            }
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            try
            {

                if (e.RowHandle != GridControl.NewItemRowHandle)
                {

                    // if (_AdapterGridview.Table.Rows[e.RowHandle]["DONGIA"].ToString() != "" && _AdapterGridview.Table.Rows[e.RowHandle]["SOLUONG"].ToString() != "")
                    _AdapterGridview.Table.Rows[e.RowHandle]["THANHTIEN"] = Convert.ToDecimal(_AdapterGridview.Table.Rows[e.RowHandle]["DONGIA"]) * Convert.ToDecimal(_AdapterGridview.Table.Rows[e.RowHandle]["SOLUONG"]);
                    _AdapterGridview.Table.Rows[e.RowHandle]["TIENTHUE"] = Convert.ToDecimal(_AdapterGridview.Table.Rows[e.RowHandle]["THANHTIEN"]) * Convert.ToDecimal(_AdapterGridview.Table.Rows[e.RowHandle]["PHAMTRAM_THUE"]) / 100;
                    _AdapterGridview.Table.Rows[e.RowHandle]["TIENVON"] = Convert.ToDecimal(_AdapterGridview.Table.Rows[e.RowHandle]["DONGIAVON"]) * Convert.ToDecimal(_AdapterGridview.Table.Rows[e.RowHandle]["SOLUONG"]);
                    TinhTongTien();
                }
            }
            catch
            {
            }
        }

        private void gridView1_RowLoaded(object sender, DevExpress.XtraGrid.Views.Base.RowEventArgs e)
        {

        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

        }

        private void gridView1_InitNewRow(object sender, InitNewRowEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = (DevExpress.XtraGrid.Views.Grid.GridView)sender;
            view.ActiveEditor.IsModified = true;
            gridView1.SetFocusedRowCellValue("SOLUONG", "1");
            gridView1.SetFocusedRowCellValue("PHAMTRAM_THUE", "0");
            gridView1.SetFocusedRowCellValue("TKNO", "1121");
            gridView1.SetFocusedRowCellValue("TKCO", "5111");
            gridView1.SetFocusedRowCellValue("TKTHUE", "3111");
            gridView1.SetFocusedRowCellValue("TKVON", "632");
            if (!string.IsNullOrEmpty(SOHD))
                gridView1.SetFocusedRowCellValue("STT_HOADON_BH", SOHD);
            else gridView1.SetFocusedRowCellValue("STT_HOADON_BH", SOHDTT);
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            TinhTongTien();
        }

        private void lblTongTienHang_TextChanged(object sender, EventArgs e)
        {
            lblChuTongTienHang.Text = Classpublic.DoiTienSangSo(decimal.Parse(lblTongTienHang.Text)).Trim().ToUpper();
            lblChuTongTienThue.Text = Classpublic.DoiTienSangSo(decimal.Parse(lblTongTienThue.Text)).Trim().ToUpper();
            lblChuTongTienThanhToan.Text = Classpublic.DoiTienSangSo(decimal.Parse(lblTongTienThanhToan.Text)).Trim().ToUpper();
        }
        private void TinhTongTien()
        {
            DataTable temp = (DataTable)_AdapterGridview.Table;
            if (temp != null)
            {
                for (int i = 0; i < temp.Rows.Count; i++)
                {
                    temp.Rows[i]["THANHTIEN"] = Convert.ToDecimal(temp.Rows[i]["DONGIA"]) * Convert.ToDecimal(temp.Rows[i]["SOLUONG"]);
                    temp.Rows[i]["TIENTHUE"] = Convert.ToDecimal(temp.Rows[i]["THANHTIEN"]) * Convert.ToDecimal(temp.Rows[i]["PHAMTRAM_THUE"]) / 100;
                    temp.Rows[i]["TIENVON"] = Convert.ToDecimal(temp.Rows[i]["DONGIAVON"]) * Convert.ToDecimal(temp.Rows[i]["SOLUONG"]);

                }

                decimal giatri;
                decimal sum = 0;
                decimal thue;
                decimal sumthue = 0;

                for (int i = 0; i < temp.Rows.Count; i++)
                {
                    Decimal.TryParse(temp.Rows[i]["THANHTIEN"].ToString(), out giatri);
                    Decimal.TryParse(temp.Rows[i]["TIENTHUE"].ToString(), out thue);
                    sum = sum + giatri;
                    sumthue = sumthue + thue;
                }
                lblTongTienHang.Text = sum.ToString();
                lblTongTienThue.Text = sumthue.ToString();
                lblTongTienThanhToan.Text = (sum + sumthue).ToString();
            }
        }

        private void SLUE_DVKH_EditValueChanged(object sender, EventArgs e)
        {
            DataTable dt = (DataTable)SLUE_DVKH.Properties.DataSource;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (dt.Rows[i]["MAKH"].ToString() == SLUE_DVKH.Text)
                {
                    txtKHDiaChi.Text = dt.Rows[i]["DIACHI"].ToString();
                    txtKHMaSoThue.Text = dt.Rows[i]["MASOTHUE"].ToString();
                    txtKHSDT.Text = dt.Rows[i]["SDT"].ToString();
                    txtTenKH.Text = dt.Rows[i]["TENKH"].ToString();
                    break;
                }
            }
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            DataProvider.AffectData(string.Format("delete from HOADON_BANHANG where STT_HOADON_BH='{0}'", SOHD));
                Close();
        }

        private void frmHoaDonBanHang_FormClosed(object sender, FormClosedEventArgs e)
        {
            frm.Lamtuoi();
        }

        private void simpleButton2_Click_1(object sender, EventArgs e)
        {
          DataTable  dt = _AdapterGridview.getDataTable(string.Format("select * from CHITIET_HOADON_BH ct, hanghoa hh where STT_HOADON_BH='{0}' and ct.mahang=hh.mahang", SOHD)); ;
            frmReport_HoaDonBH frm = new frmReport_HoaDonBH(dt, txtTenKH.Text, txtKHDiaChi.Text, txtKHSDT.Text, txtKHMaSoThue.Text, DateTime.Parse(txtNgayHD.Text), lblChuTongTienHang.Text,SOHD);
            frm.Show();
        }

        private void panelControl1_Paint(object sender, PaintEventArgs e)
        {

        }


    }
}